# coding=utf-8
"""
该模块包含系统开发、运行的底层工具

@see: 参考资料链接等等
@license: GPL
@todo:
@bug:

"""
from django.core.paginator import Paginator
from django.db.models.query import QuerySet


class Page(object):
    '''
      分页显示工具，
      该工具封装了django的Paginator。
    '''

    def __init__(self, objs, c, p):
        '''
        @type objs: list
        @param objs: 需要分页显示的对象列表。
        @type c: number
        @param c: 每页的对象数量-
        @type p: number
        @param p: 要显示第几页

        @rtype: Page
        @return: 返回Page对象
        '''

        # 对未排序的QuerySet默认使用pk排序
        try:
            if isinstance(objs, QuerySet) and objs.ordered is False:
                objs = objs.order_by('pk')
        except:
            pass

        self._pageor = Paginator(objs, c)
        try:
            self._page = self._pageor.page(p)
        except:
            self._page = self._pageor.page(1)
        self.objs = objs
        self.count = self._pageor.count
        self.ac = self._pageor.count
        self.num_pages = self._pageor.num_pages
        self.per_page = c
        self.start_page = 1
        self.sp = 1
        self.end_page = self.num_pages
        self.ep = self.num_pages

        self.object_list = self._page.object_list
        self.num_cur_page = self._page.number
        self.cp = self._page.number
        self.start_index = self._page.start_index()
        self.end_index = self._page.end_index()

        _t = [self.num_cur_page]
        while len(_t) < 5 and (_t[len(_t) - 1] < self.num_pages or _t[0] > 1):
            if _t[0] > 1:
                _t = [_t[0] - 1] + _t
            if _t[len(_t) - 1] < self.num_pages:
                _t = _t + [_t[len(_t) - 1] + 1]
        if len(_t) == 1:
            _t = []
        self.page_range = _t

    def has_next(self):
        '''
           判断是否有后一页
        @rtype: boolean
        '''
        return self._page.has_next()

    def has_previous(self):
        '''
           判断是否有前一页
        @rtype: boolean
        '''
        return self._page.has_previous()

    def next_page_number(self):
        '''
           返回后一页的页号
        @rtype: number
        '''
        return self._page.next_page_number()

    def previous_page_number(self):
        '''
           返回前一页的页号
        @rtype: number
        '''
        return self._page.previous_page_number()

    def get_verbose_name(self):
        return self.objs.model._meta.verbose_name

    def get_model_name(self):
        return self.objs.model._meta.model_name

    def get_columns_verbose_names(self):
        return [f.verbose_name for f in self.objs.model._meta.fields]


def get_page(objs, request, perpage=20):
    '''
      方便程序调用，返回Page对象

    @type objs: list
    @param objs: 需要分页显示的对象列表。
    @type request: django httprequest
    @param request: request中包含page变量，默认是首页
    @type perpage: number
    @param perpage: 每页的对象数量，默认数值是5

    @rtype: Page
    @return: 返回Page对象
    '''
    try:
        page_num = int(request.GET.get('page', 1))
    except ValueError:
        page_num = 1

    try:
        perpage = int(request.GET.get('perpage', perpage))
    except ValueError:
        perpage = perpage
    return Page(objs, perpage, page_num)


def gen_url(url, query=None, argss=None):
    """
    生成URL, params拼接到url_str后
    :param url:
    :return:
    """

    def _load_param(string):
        from urlparse import urlparse, parse_qs
        string = string or ""
        params = parse_qs(urlparse(string).query)
        print {k: v[0] for k, v in params.items()}, "$$$$$$$$$$$$$$$"
        return {k: v[0] for k, v in params.items()}

    params = _load_param(url)
    params.update(_load_param(query))
    params.update(argss or {})  # 参数合并

    path = url.split("?")[0]
    if not params: return path  # 直接返回

    print params, "$$$$$$$$$$$$$$"

    conditions = ["%s=%s" % (k, v) for k, v in params.items()]
    return "%s?%s" % (path, "&".join(conditions))  # 结果拼装
